package org.babygo.connect.handler.server.msg;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import org.babygo.connect.NettyFileOperator;
import org.babygo.connect.util.CommonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Sharable
public class ServerConnectInboundHandler extends ChannelInboundHandlerAdapter {
	private Logger log = LoggerFactory.getLogger(ServerConnectInboundHandler.class);

	@Override
	public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
		String[] ipAndPort = CommonUtil.getIpAndPort(ctx.channel().remoteAddress());
		NettyFileOperator.OPERTATOR.remotClientClosed(ipAndPort[0],ipAndPort[1]);
	}

	@Override
	public void channelActive(final ChannelHandlerContext ctx) throws Exception {
		log.info("Tran-channelActive");
		if (!NettyFileOperator.OPERTATOR.receiveNewConnect(ctx.channel().remoteAddress().toString())){
			NettyFileOperator.OPERTATOR.writeLog("[服务端]来自" + ctx.channel().remoteAddress().toString() + "的连接被拒绝!");
			ctx.close();
		}
		NettyFileOperator.OPERTATOR.writeLog("[服务端]来自" + ctx.channel().remoteAddress().toString() + "的连接被接收!");
		String[] ipAndPort = CommonUtil.getIpAndPort(ctx.channel().remoteAddress());
		NettyFileOperator.OPERTATOR.acceptNewClientConnector(ipAndPort[0], ipAndPort[1]);
		((NettyFileOperator)NettyFileOperator.OPERTATOR.getServerOper()).getNettyService().addNewClient(ipAndPort[0], ipAndPort[1], ctx.channel());
	}
}
